# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(plyr)
library(gridExtra)
library(ggpubr)
library(egg)
library(lemon)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
    select(c("SampleID", "ClassNote")) %>%
    mutate(ClassNote = as.character(ClassNote)) %>%
    mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote)))

sampleIds <- sampleInfo %>%
    arrange(ClassNote) %>%
    .$SampleID

sampleColDf <- read.csv(opt$sc, header = T, stringsAsFactors = F, comment.char = "") %>%
select(c("ClassNote", "col"))
sampleCols <- sampleColDf %>%
deframe()

diffData <- read_csv("Markers.csv")

if (nrow(diffData) == 0) {
  quit(status = 0)
}

diffNames <- diffData %>%
.$Metabolite

orignalData <- read.csv(opt$i, header = T, check.names = F, stringsAsFactors = F) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    select(c("Metabolite", sampleIds)) %>%
    filter(Metabolite %in% diffNames)

data <- read.csv(opt$i, header = T, check.names = F, stringsAsFactors = F) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    select(c("Metabolite", sampleIds)) %>%
    filter(Metabolite %in% diffNames) %>%
    gather("SampleID", "Value", - Metabolite, factor_key = T) %>%
    spread(Metabolite, "Value") %>%
    mutate_at(vars(- "SampleID"), scale) %>%
    mutate_at(vars(- "SampleID"), function(x) {
        x1 <- x %>%
            unlist()
        return(x1)
    }) %>%
    as.data.frame() %>%
    arrange(factor(SampleID, levels = sampleIds)) %>%
    column_to_rownames("SampleID")

head(data)

parent <- "./"
fileName <- paste0(parent, "/Markers_Z_Score.csv")

write.csv(data, fileName)

groups <- unique(sampleInfo$ClassNote)
group1Name <- groups[1]
group2Name <- groups[2]

sortData <- orignalData %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        group1Sample <- sampleInfo %>%
            filter(ClassNote == groups[1]) %>%
            .$SampleID
        group2Sample <- sampleInfo %>%
            filter(ClassNote == groups[2]) %>%
            .$SampleID
        group1Data <- result[group1Sample] %>% unlist
        group2Data <- result[group2Sample] %>% unlist
        mean1Name <- paste0(group1Name, ".Mean")
        result[, mean1Name] <- mean(group1Data)
        mean2Name <- paste0(group2Name, ".Mean")
        result[, mean2Name] = mean(group2Data)
        result$FC <- result[, mean2Name] / result[, mean1Name]
        result[, "min1"] <- min(group1Data)
        result[, "min2"] <- min(group2Data)
        result
    }) %>%
    select(- sampleIds) %>%
    as.data.frame() %>%
    mutate(logFc = log(FC)) %>%
    arrange(min1)


print("==allData==")
sortData

plotData <- data %>%
    rownames_to_column("SampleID") %>%
    gather("Metabolite", "Value", - SampleID) %>%
    left_join(sampleInfo, by = c("SampleID")) %>%
    mutate(Metabolite = factor(Metabolite, levels = sortData$Metabolite))

head(plotData)

p <- ggplot(plotData, mapping = aes(x = Value, y = Metabolite, fill = ClassNote)) +
    ylab("") +
    xlab("Z score") +
    theme_bw(base_size = 8.8, base_family = "Times") +
    theme(axis.text.x = element_text(size = 10, hjust = 1, vjust = 1), legend.position = 'right',
    legend.text = element_text(size = 9), legend.title = element_text(size = 11), axis.text.y = element_text(size = 6),
    axis.title.y = element_text(size = 11), axis.title.x = element_text(size = 12), panel.grid.major.x = element_blank(),
    panel.border = element_rect(size = 0.75), panel.grid.minor.x = element_blank(), panel.grid.major.y = element_line(
    linetype = 2, color = "#BEBEBE")
    ) +
    geom_point(shape = 21, color = "black", size = 2, alpha = 0.75,stroke=0.2) +
    scale_fill_manual("", values = sampleCols)

minHeight<-1
rowNum <- nrow(orignalData)
height <- max(minHeight + (rowNum - 10) * 0.1, minHeight) + 2
pdfFileName <- paste0(parent, "/Markers_Z_Score_Plot.pdf")
ggsave(limitsize = FALSE,pdfFileName, p, width = 6, height = height)

